<--!
Copyright (c) 2010, Goodwine & Tibia ML
Licensed under new BSD License.
Please read the LICENSE.TXT included in the root folder for more information.
-->
<html>
<head>
	<script src="common.js"></script>
	<script>
		var options;
		var stamina;

		// Dynamically load jQuery with XHR
		function loadJQuery(callback) {
			var xhr = new XMLHttpRequest();
			xhr.onreadystatechange = function(data) {
				if (xhr.readyState == 4) {
					if (xhr.status == 200) {
						callback(xhr.responseText);
					} else {
						callback(null);
					}
				}
			}
			var url = 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js';
			xhr.open('GET', url, true);
			xhr.send();
		};
	
	// XHR to get the 'Who is Online?' page of the given world and use it as an argument for callback.
  function getPlayersOnlineHTML(callback, world) {
      var xhr = new XMLHttpRequest();
      xhr.onreadystatechange = function(data) 
      {
        if (xhr.readyState == 4)
          if (xhr.status == 200)
          {
            var data = xhr.responseText;
            callback(data, world);
          }
          else
            callback(null);
      }
      var url = 'http://www.tibia.com/community/?subtopic=worlds&world='+world;
      xhr.open('GET', url, true);
      xhr.send();
  }
  
	// Handle various requests made by the content scripts.
  function onRequest(request, sender, callback) {
		// Request 'Who is Online' of the given world.
    if (request.world != null && !JSON.parse(localStorage.indicator_disabled))
      getPlayersOnlineHTML(callback, request.world);
		// Request a localStorage value in the extension to be used by the content scripts.
    else if(request.key != null)
			callback(localStorage.getItem(request.key));
		// Request the icons that link to some websites.
		else if(request.icons != null) {
			x = [];
			for(var i in request.icons)
				x[i] = localStorage.getItem(request.icons[i]);
			callback(x);
		}
		// Request the character's information page.
		else if(request.character != null)
			getCharacterInfo(request.character, callback);
		// Handle the action requested.
		else if(request.action != null)
			switch(request.action) {
					// Load jQuery dinamically.
					case 'loadJQuery':
						loadJQuery(callback);
						break;
					// Add Zoomer images to history.
					case 'addUrlToHistory':
						chrome.history.addUrl({url: request.url});
						break;
					// Load Zoomer options to the content scripts.
					case 'getOptions':
						callback(options);
						break;
					// Update options if changed.
					case 'optionsChanged':
						options = request.options;
						break;
					// Load link options to content scripts.
					case 'opLinkPages':
						callback(JSON.parse(localStorage.opLinkPages));
						break;
					// Callback the charsOnline in sessionStorage.
					case 'getSessionStorage':
						callback(sessionStorage.getItem(request.key));
					// Save stamina for notifications thru Tibia ML.
					case 'saveStamina':
						// Objects are hack to simulate <select> and <object> elements.
						saveStamina(request.hours, request.minutes, request.premmy);
						callback({'hours':request.hours, 'minutes':request.minutes});
					break;
				}
  }
  chrome.extension.onRequest.addListener(onRequest);
	
	// Listen when the Browser Action button gets clicked and open the options page.
  chrome.browserAction.onClicked.addListener(function(tab) {
		chrome.tabs.create({'url':chrome.extension.getURL('options.html')});
  });
	// Check the stamina each 3 minutes and on start.
  notifyStamina();
  function notifyStamina()
  {
		stamina = loadStamina();
		setTimeout('notifyStamina()', 1000*60*3);
		// If stamina was full before, no need to notify.
		if(stamina.milestone == 42)
			return;
		// Pretty printed time in 24 hrs.
		var time = /(..)(:..)/(Date());
		var hour = time[1] % 24;
		var zero = time[1] < 10 ? '0' : '';
		// Calculate stamina.
		var stam = calcStamina();
		var body = false;
		// Notify if stamina is full.
		if(stam.hours >= 42) {
			stamina.milestone = 42;
			stamina.hours = 42;
			body = 'Your character has full stamina!';
		}
		// Notify if you reached the bonus time and you are premmy as well.
		else if(stamina.premmy && stamina.milestone < 40 && stam.hours > 40) {
			stamina.milestone = 40;
			body = 'Your character has 40hrs of stamina left.';
		}
		// Notify when you reached 14 hours of stamina and are able to loot again.
		else if(stamina.milestone < 14 && stam.hours >= 14) {
			stamina.milestone = 14;
			body = 'Your character has 14hrs of stamina left.';
		}
		// Create the notification.
		if(body) {
			var notification = webkitNotifications.createNotification('icons/48.png', zero + hour + time[2], body);
			notification.show();
			setTimeout(function (){ notification.cancel(); }, 6000);
		}
		localStorage.stamina = JSON.stringify(stamina);
  }
  
	// Request the character's information page.
  function getCharacterInfo(character, callback)
  {
		var xhr = new XMLHttpRequest();
		xhr.onreadystatechange = function(data) 
		{
			// Loading screen.
			if (xhr.readyState == 1)
			{
				var bg = document.createElement('div');
				var sq = document.createElement('div');
				bg.appendChild(sq);
				bg.style.zIndex = "9359";
				bg.style.height = "100%";
				bg.style.width = "100%";
				bg.style.position = "fixed";
				bg.style.top = "0";
				bg.style.left = "0";
				bg.style.opacity = "0.5";
				bg.style.background = "#000000";
				sq.style.height = "50px";
				sq.style.width = "50px";
				sq.style.borderRadius = "30px";
				sq.style.margin="0";
				sq.style.verticalAlign = "middle";
				sq.style.background = "#FFFFFF";
			}
			// Callback the data if exists.
			if (xhr.readyState == 4)
				if (xhr.status == 200)
				{
					var data = xhr.responseText;
					callback(data);
				}
				else
					callback(null);
		}
		var url = 'http://www.tibia.com/community/?subtopic=characters&name='+character;
		xhr.open('GET', url, true);
		xhr.send();
  }
	
	// Notify on character log in each 5 minutes.
	localStorage.charNotOnStart = localStorage.charNotOnStart || true;
	// Notify on start.
	if(JSON.parse(localStorage.charNotOnStart))
		notifyCharacters();
  setInterval('notifyCharacters()', 1000*60*5);
  function notifyCharacters()
  {
		// Get the list of the worlds to be loaded.
		localStorage.characters = localStorage.characters || "";
		var worlds = Array();
		var temp = localStorage.characters.split(' | ');
		for(var i in temp)
		{
			var values = temp[i].split(' , ');
			if(values[1])
				var add = true;
			else
				var add = false;
			for(var k in worlds)
			{
				if(worlds[k] == values[1])
					add = false;
			}
			if(add)
				worlds.push(values[1]);
		}
		// Check on each world if the characters are online.
		for(var i in worlds) {
			getPlayersOnlineHTML(checkCharacters, worlds[i]);
		}
  }
	
	// Verify if there is a character online to make a notification.
  function checkCharacters(data, world)
  {
		var time = /(..)(:..)/(Date());              // The prettyprinted time.
		var hour = time[1] % 24;               // The prettyprinted hour.
		var zero = time[1] < 10 ? '0' : ''; // The period of the day.
		sessionStorage.charsOnline = sessionStorage.charsOnline || "";
  	var temp = localStorage.characters.split(' | ');
  	data = data.replace(/(\xa0|&#160;|&nbsp;|\+)/ig, " ");
		// Parse the character list.
		for(var i=0 in temp)
		{
			var values = temp[i].split(' , ');
			if(values[1] != world)
				continue;
			// Check if the character is listed as online.
			if(data.match(new RegExp('>'+values[0]+'<\\/a>', 'i')))
			{
				var sendNote = true;
				var charsIn = sessionStorage.charsOnline.split(' | ');
				for(var j=0 in charsIn)
					if(charsIn[j] == values[0]) {
						console.log(zero + hour + time[2] + ': '+ values[0]+' not Added.');
						sendNote = false;
						break;
					}
				// Notify if character is online.
				if(sendNote)
				{
					sessionStorage.charsOnline += ' | ' + values[0];
					var notification = webkitNotifications.createNotification(
						'icons/48.png',                      // The image.
						zero + hour + time[2], // The title.
						values[0] + ' is online in '+world+'!'      // The body.
					);
					notification.show();
					setTimeout(function (){ notification.cancel(); }, 5000);
					chrome.extension.sendRequest({'updateCharList':true});
				}
			}
			// If the character was online and created a notification, when he goes offline, notify too.
			else
			{
				var sendNote = false;
				var charsIn = sessionStorage.charsOnline.split(' | ');
				for(var j=0 in charsIn)
					if(charsIn[j] == values[0])
					{
						sendNote = true;
						var newTemp = [];
						var x;
						while(x = charsIn.pop())
						{
							if(values[0] != x)
								newTemp.push(x);
						}
						newTemp.reverse();
						sessionStorage.charsOnline = newTemp.join(' | ');
						break;
					}
				if(sendNote)
				{
					var notification = webkitNotifications.createNotification(
						'icons/48.png',
						zero + hour + time[2],
						values[0] + ' is offline!'
					);
					notification.show();
					setTimeout(function (){ notification.cancel(); }, 5000);
					chrome.extension.sendRequest({'updateCharList':true});
				}
			}
		}
		// Hack to pass the charsOnline from here to options page.
		localStorage.charsOnline = sessionStorage.charsOnline;
  }
  
</script>
</head>
<body onLoad="initialize();">
	<script>
	</script>
</body>
</html>